import request from "@/utils/request";

const CHAT_BASE_URL = "/wz/api/chat/ai";

/** 聊天消息 */
export interface Message {
  /** 消息ID */
  id: string;
  /** 会话ID */
  sessionId: string;
  /** 用户ID */
  userId: string;
  /** 消息内容 */
  content: string;
  /** 消息类型（user/assistant） */
  role: string;
  /** 创建时间 */
  createTime: string;
}

/** 聊天会话 */
export interface ChatSession {
  /** 会话ID */
  id: string;
  /** 用户ID */
  userId: string;
  /** 会话标题 */
  title: string;
  /** 创建时间 */
  createTime: string;
  /** 最后更新时间 */
  updateTime: string;
}

/** 聊天会话管理接口 */
export class ChatAPI {
  /**
   * 获取聊天记录
   *
   * @param sessionId 会话ID
   * @returns 聊天消息列表
   */
  static getMessages(sessionId: string) {
    return request<any, Message[]>({
      url: `${CHAT_BASE_URL}/messages`,
      method: "get",
      params: { sessionId },
    });
  }

  /**
   * 获取会话列表
   *
   * @param userId 用户ID
   * @returns 会话列表
   */
  static getSessions(userId: string) {
    console.log("Requesting sessions for user:", userId);
    return request<any, ChatSession[]>({
      url: `${CHAT_BASE_URL}/sessions`,
      method: "get",
      params: { userId },
    }).then((res) => {
      console.log("Sessions response:", res);
      return res;
    });
  }

  /**
   * 发送聊天消息
   *
   * @param message 消息内容
   * @param sessionId 会话ID
   * @param userId 用户ID
   * @returns 聊天回复内容
   */
  static async sendMessage(message: string, sessionId: string, userId: string) {
    if (!sessionId) {
      const session = await this.createSession(
        userId,
        `新会话 ${new Date().toLocaleString()}`
      );
      sessionId = session.id;
    }

    return new Promise<string>((resolve, reject) => {
      let fullResponse = "";
      const eventSource = new EventSource(
        `${import.meta.env.VITE_APP_BASE_API}/${CHAT_BASE_URL}/generateStream?message=${encodeURIComponent(message)}&sessionId=${encodeURIComponent(sessionId)}&userId=${encodeURIComponent(userId)}`
      );

      eventSource.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          if (data.content) {
            fullResponse += data.content;
          }
        } catch (e) {
          if (event.data === "[DONE]") {
            eventSource.close();
            resolve(fullResponse);
          }
        }
      };

      eventSource.onerror = (error) => {
        eventSource.close();
        reject(error);
      };

      eventSource.addEventListener("done", () => {
        eventSource.close();
        resolve();
      });
    });
  }
}
